<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\CommonException;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\Carts;
use App\Models\CouponUsers;
use App\Models\Order;
use App\Models\ProcutSku;
use App\Models\Products;
use App\Models\Reservation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    /**
     * 生成預約訂單
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createReservation(Request $request)
    {
        $params = $request->all();

        $res = Reservation::create([
            'product_id' => $params['product_id'],
            'contact_name' => $params['contact_name'],
            'email' => $params['email'],
            'mobile' => $params['mobile'],
            'start_time' => $params['start_time'],
            'users_id' => $request->userId,
            'reservation_on' => $this->createOrderOn()
        ]);

        $data = Reservation::with('product')->where('id', $res->id)->first();

        if ($res->product_id) return $this->success($data);
        return $this->apiError('生成訂單失敗');
    }

    /**
     * 创建订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
//    public function createOrder(Request $request)
//    {
//
//        $user=\request()->userId;
//
//        if($request->input('coupon_id')){
//            if(!$res= CouponUsers::where('coupon_id',$request->input('coupon_id'))->where('users_id',$user)->first()){
//                return $this->apiError('該優惠券已失效！');
//            }
//           $coupon= $this->selectCoupon($request->input('coupon_id'),$user);
//        }
//
//        $params=$request->all();
//
//       if($params['order_type']==1){
//
//        if(empty($params['carts_id'])){
//
//            $product_ids=array_column($params['product'],null,'id');
//
//            $data=Products::select('id','name','price','num','cover_pic','integral','is_spec')->whereIn('id',array_keys($product_ids))->get()->toArray();
//            // if(!$data) return $this->apiError();
//
//            foreach ($data as &$item){
//                if($item['num']-$product_ids[$item['id']]['count']<0){
//                    return $this->apiError($item['name'].'庫存不足');
//                }
//                $totalPrice[]=$product_ids[$item['id']]['count']*$item['price']; //总价格
//                $item['count']=$product_ids[$item['id']]['count'];
//            }
//
//            }else{
//
//                $data=Carts::where('users_id',$user)->whereIn('id',explode(',',$params['carts_id']))->get()->toArray();
//
//               if(!$data) return $this->apiError('購物車異常');
//
//               //單規格
//                $product=Products::select('id','name','price','num','cover_pic','integral','is_spec')->where('is_spec',0)->whereIn('id',array_column($data,'products_id'))->get()->toArray();
//
//                //多規格
//                $product_sku=Products::select('id','name','price','num','cover_pic','integral','is_spec')->where('is_spec',1)->whereIn('id',array_column($data,'products_id'))->get()->toArray();
//
//
////                foreach ($product as $item){
////                    if($item['is_spec']==1){
////                        $sku=   ProcutSku::whereIn('id',array_column($data,'product_sku_id'))->get()->toArray();
////                    }
////                }
//
//
//
//                $carts=array_column($product,null,'id');
//           $sku= ProcutSku::whereIn('id',array_column($data,'product_sku_id'))->get()->toArray();
//
//           $sku=array_column($sku,null,'id');
//
//                foreach($data as &$items){
//
//                    //處理多規格
//                    if($items['product_sku_id']>0){
//
//                       $items['price']= $sku[$items['product_sku_id']]['price'];
//
//
//                        $arr['id']= $items['products_id'];
//                        $arr['name']=$carts[$items['products_id']]['name'];
//                        $arr['price']=$carts[$items['products_id']]['price'];
//                        $arr['cover_pic']=$carts[$items['products_id']]['cover_pic'];
//                        $arr['integral']=$carts[$items['products_id']]['integral'];
//                        $totalPrice[]=$items['num']*$carts[$items['products_id']]['price']; //总价格
//                        $items['count']=$items['num'];
//                        unset($items['products_id']);
//
//                    }else{
//
//                        if( $carts[$items['products_id']]['num']-$items['num']<0){
//
//                            return $this->apiError($carts[$items['products_id']]['name'].'庫存不足');
//
//                        }
//                        $items['id']= $items['products_id'];
//                        $items['name']=$carts[$items['products_id']]['name'];
//                        $items['price']=$carts[$items['products_id']]['price'];
//                        $items['cover_pic']=$carts[$items['products_id']]['cover_pic'];
//                        $items['integral']=$carts[$items['products_id']]['integral'];
//                        $totalPrice[]=$items['num']*$carts[$items['products_id']]['price']; //总价格
//                        $items['count']=$items['num'];
//                        unset($items['products_id']);
//                    }
//
//
//
//                }
////                Carts::destroy(explode(',',$params['carts_id']));
//            }
//
//            $address=DB::table('address')->where('id',$request->userID)->first();
//
//                $totalPrices=array_sum($totalPrice);
//
//
//           $res =Order::create([
//                'order_no'=>$this->createOrderOn(),
//                'pay_price'=>empty($coupon)?$totalPrices:$this->compute($coupon,$totalPrices),
//                'address'=>json_encode($address),
//                'product_item'=>json_encode($data),
//                'users_id'=>$user,
//               'order_type'=>$params['order_type'],
//               'pay_mode'=>$params['pay_mode']
//            ]);
//           if(!empty($coupon)) CouponUsers::where('coupon_id',$request->input('coupon_id'))->where('users_id',$user)->delete();
//            return $this->success(['order_id'=>$res->id]);
//            // 预约订单
//       }elseif($params['order_type']==2){
//
//           $product_ids=array_column($params['product'],null,'id');
//           $data=Products::select('id','name','price','num','cover_pic','integral')->whereIn('id',array_keys($product_ids))->get()->toArray();
//
//           $res =Order::create([
//               'order_no'=>$this->createOrderOn(),
//               'pay_price'=>empty($coupon)?$data[0]['price']:$this->compute($coupon,$data[0]['price']),
//               'time'=>$params['time'],
//               'date'=>$params['date'],
//               'users_id'=>$user,
//               'product_item'=>json_encode($data[0]),
//               'address'=>json_encode($params['address']),
//               'order_type'=>$params['order_type'],
//               'pay_mode'=>$params['pay_mode'],
//               'products_id'=>$data[0]['id']
//           ]);
//
//            if(!empty($coupon)) CouponUsers::where('coupon_id',$request->input('coupon_id'))->where('users_id',$user)->delete();
//
//          $goods=Products::where('id',$res->products_id)->select('id','name','price','units','cover_pic')->first();
//          $order=[
//              'order_id'=>$res->id,
//              'time'=>$res->time,
//              'date'=>$res->date,
//              'order_time'=>date('Y-m-d H:i'),
//              'pay_mode'=>$res->pay_mode,
//              'order_no'=>$res->order_no,
//              'address'=>$res->address,
//              'goods'=>$goods
//          ];
//           return $this->success($order);
//       }
//    }


    public function createOrder(Request $request)
    {
        $user = \request()->userId;
        $order_type = $request->input('order_type');
        $total_price = $request->input('total_price');
        $carts_id = $request->input('carts_id');
        $time = $request->input('time');
        $address=$request->input('address',[]);
        $person=$request->input('person');

        $pay_mode=$request->input('pay_mode');
        if ($request->input('coupon_id')) {
            if (!$res = CouponUsers::where('coupon_id', $request->input('coupon_id'))->where('users_id', $user)->first()) {
                return $this->apiError('該優惠券已失效！');
            }
            $coupon = $this->selectCoupon($request->input('coupon_id'), $user);
        }

//        $carts= DB::table('carts')->whereIn()->get();

            $carts=    Carts::with('products','sku')->whereIn('id',explode(',',$carts_id))->get();
        if(!$order_type==3){
            //庫存檢測
            foreach ($carts as $v){
                if($v->product_sku_id==0){
                    if($v->num >$v->products->num ) return $this->apiError($v->products->name.'庫存不足');
                }else{

                    if($v->num >$v->sku->stock) return $this->apiError('該規格庫存不足');
                }
            }
        }


        $data=Products::select('id','name','price','num','cover_pic','integral')->whereIn('id',array_column( Carts::with('products','sku')->whereIn('id',explode(',',$carts_id))->get()->toArray(),'products_id'))->get()->toArray();



        //美食外送1
        if ($order_type == 1) {

            $order_id = Order::create([
                'order_no' => $this->createOrderOn(),
                'users_id' => $user,
                'pay_price' => empty($coupon) ? $total_price : $this->compute($coupon, $total_price),
                'time'=>$time,
                'product_item'=>json_encode($data),
                'order_type'=>$order_type,
                'address'=>json_encode($address),
                'pay_model'=>$pay_mode
            ]);

            // 自取2
        } elseif ($order_type == 2) {

            $order_id = Order::create([
                'order_no' => $this->createOrderOn(),
                'users_id' => $user,
                'pay_price' => empty($coupon) ? $total_price : $this->compute($coupon, $total_price),
                'time'=>$time,
                'product_item'=>json_encode($data),
                'order_type'=>$order_type,
                'address'=>json_encode($address),
                'pay_model'=>$pay_mode
            ]);
            // 预约3
        } else {

            $order_id = Order::create([
                'order_no' => $this->createOrderOn(),
                'users_id' => $user,
                'pay_price' => empty($coupon) ? $total_price : $this->compute($coupon, $total_price),
                'time'=>$time,
                'product_item'=>json_encode($data),
                'order_type'=>$order_type,
                'address'=>json_encode($address),
                'person'=> $person,
                'pay_model'=>$pay_mode
            ]);
        }
        $order_details=[];

        foreach ($carts as $item){
            $order_details[]=[
                'order_id'=>$order_id->id,
                'products_id'=>$item->products_id,
                'num'=>$item->num,
                'users_id'=>$user,
                'sku_id'=>$item->product_sku_id ?? 0
            ];
        }

        $res=DB::table('order_details')->insert($order_details);
        Carts::with('products','sku')->whereIn('id',explode(',',$carts_id))->delete();

        return $this->success(['order_id'=>$order_id->id]);
    }




    /**
     * 計算折扣價
     * @param $coupon
     * @param $totalPrices
     * @return float|int
     */

    protected function compute($coupon, $totalPrices)
    {


        //满减 满折 立减 立折
        if ($coupon['coupon'][0]['type'] == 10 && $totalPrices > $coupon['coupon'][0]['condition']) {

            $moeny = $totalPrices - $coupon['coupon'][0]['money'];

        } elseif ($coupon['coupon'][0]['type'] == 20 && $totalPrices > $coupon['coupon'][0]['condition']) {

            $moeny = $totalPrices * sprintf('0.%s', $coupon['coupon'][0]['money']);
        } elseif ($coupon['coupon'][0]['type'] == 30) {

            $moeny = $totalPrices - $coupon['coupon'][0]['money'];
        } else {

            $moeny = $totalPrices * sprintf('0.%s', $coupon['coupon'][0]['money']);
        }
        return $moeny;
    }

    /**
     * 查询是否有该优惠券
     * @param $id
     * @param $user
     * @return bool
     */
    protected function selectCoupon($id, $user)
    {

        return CouponUsers::with('coupon')->where('coupon_id', $id)->where('users_id', $user)->first()->toArray();

    }

    /**
     * 訂單詳情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderInfo(Request $request)
    {


        $id = $request->input('id');
        if (empty($id)) return $this->apiError('訂單id不能為空');
        $data= Order::with('detail.products')
            ->where('id',$id)
            ->where('users_id',$request->userId)
            ->select('id','order_no','status','users_id','pay_price','address','pay_mode','created_at','delivery_type','order_type','time','person')
            ->get()->toArray();

        return $this->success($data);
    }


    /**
     * 查看全部订单
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderAll(Request $request)
    {
        $user=$request->userId;
        $order_type=$request->input('order_type');

        if($order_type==3) {
          $data=  Order::where('users_id', $user)->where('order_type',3)->orderBy('id','desc')->paginate(10);

        }else{
            $data= Order::where('users_id', $user)->where('order_type','!=',3)->orderBy('id','desc')->paginate(10);
        }
        return $this->success($data);
    }

    /**
     * 確認收貨
     */
    public function affirmOrder(Request $request)
    {
        $order_id = $request->input('order_id');
        $user = $request->UserId;
        $order = Order::where('id', $order_id)->first();
        if ($order->status == 10) return $this->apiError('該訂單未支付');
        Order::where('id', $order_id)->update(['status' => 50]);
        return $this->success();
    }

    /**
     * 查看全部預約訂單
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getReservationAll(Request $request)
    {


        $status = $request->input('status');
        if ($status == 1) {
            $order = Order::where('order_type', 2)->where('users_id', $request->userId)->where('status', 50)->orderBy('id', 'desc')->paginate($request->input('limit'));
        } else {
            $order = Order::where('order_type', 2)->where('users_id', $request->userId)->whereIn('status', [10, 20, 30, 40])->orderBy('id', 'desc')->paginate($request->input('limit'));
        }
        return $this->success($order);
    }

    /**
     * 生成订单号
     * @return string
     */
    public function createOrderOn()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}
